//
//  SendTrendViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2017/5/9.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "SendTrendViewController.h"
#import "TZImagePickerController.h"
#import "PIMWPhotoBrowserController.h"
#import "PostImageCell.h"
#import "GetPhoto.h"
#import "MWPhoto.h"
#define kMaxCount 9 //最大选取照片数

@interface SendTrendViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,TZImagePickerControllerDelegate,UITextViewDelegate> {
    NSMutableArray *_selectImageArray;
    NSMutableArray *_fileNameArray;
    NSMutableArray *_filePathArray;
}
@property (weak, nonatomic) IBOutlet UITextView *descTextView;
@property (weak, nonatomic) IBOutlet UILabel *placeHolder;
@property (weak, nonatomic) IBOutlet UICollectionView *imageCollectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) UIImage *addImage;

@end

@implementation SendTrendViewController
static NSString *postImageCellID = @"postImageCellID";

#pragma mark -- 网络请求
- (void)SendTrendRequestWithContent:(NSString *)content {
    NSData *dataName = [NSJSONSerialization dataWithJSONObject:_fileNameArray options:NSJSONWritingPrettyPrinted error:nil];
    NSData *dataPath = [NSJSONSerialization dataWithJSONObject:_filePathArray options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString *jsonStringName = [[NSString alloc] initWithData:dataName encoding:NSUTF8StringEncoding];
    NSString *jsonStringPath = [[NSString alloc] initWithData:dataPath encoding:NSUTF8StringEncoding];
                            

    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"description":@"我是第二条动态,,.....",
                           @"path":jsonStringPath,
                           @"file":jsonStringName
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kSendTrend];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kStarRoomTrendListNotifica object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

- (UICollectionViewFlowLayout *)layout
{
    if (!_layout) {
        _layout = [[UICollectionViewFlowLayout alloc] init];
    }
    return _layout;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpUI];
    
    [self setNav];
}

- (void)setUpUI {
     _selectImageArray = [NSMutableArray arrayWithCapacity:1];
    _fileNameArray = [NSMutableArray arrayWithCapacity:1];
    _filePathArray = [NSMutableArray arrayWithCapacity:1];
    self.descTextView.delegate = self;
    [self.imageCollectionView setCollectionViewLayout:self.layout];
    [self.imageCollectionView registerClass:[PostImageCell class] forCellWithReuseIdentifier:postImageCellID];
    self.imageCollectionView.delegate = self;
    self.imageCollectionView.dataSource = self;
    self.addImage = kSET_IMAGE(@"addImage");
    [_selectImageArray addObject:self.addImage];
}

- (void)setNav {
    self.navigationItem.title = @"写动态";
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [rightBtn addTarget:self action:@selector(SendTrend:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitle:@"发布" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = UIFont(14);
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = item;
}


#pragma mark -- 发布动态
- (void)SendTrend:(UIButton *)sender {
    [self showHUDInView:self.view title:@"发布中..."];
    UIImage *lastImage  = [_selectImageArray lastObject];
    if ([lastImage isEqual:self.addImage]) {
        [_selectImageArray removeLastObject];
    }
    [_filePathArray removeAllObjects];
    [_fileNameArray removeAllObjects];
    __block  int k = 0;
    if (_selectImageArray.count) {
        for (int i = 0; i<_selectImageArray.count; i++) {
            UIImage *image = _selectImageArray[i];
            NSDictionary *dict = @{@"udid":User_ID,
                                   @"token":TOKEN
                                   };
            NSString *urlString = [TEST_URL stringByAppendingString:kUploadImage];
            QZHUploadFormData *uploadData = [[QZHUploadFormData alloc] init];
            uploadData.imageData = UIImageJPEGRepresentation(image,0.5);
            uploadData.dataType = DataTypeJpeg;
            uploadData.name = @"img";
            uploadData.fileName = @"image.jpg";
            [NetworkTools UploadRequestWithParams:dict UrlString:urlString uploadParams:uploadData successBlock:^(id responseObject) {
                [self hideHUD];
                if ([responseObject[@"code"] intValue] == 200) {
                    k = k + 1;
                    NSString *imageFile = responseObject[@"data"][@"file"];
                    NSString *imagePath = responseObject[@"data"][@"path"];
                    [_fileNameArray addObject:imageFile];
                    [_filePathArray addObject:imagePath];
                    
                    
                    if (k == _selectImageArray.count ) {
                        [self SendTrendRequestWithContent:@"我的第一条动态"];
                    }
                }else {
                    [self showTitle:@"上传失败,重试"];
                }
            } failureBlock:^(NSError *error) {
                [self hideHUD];
            } showHUD:NO];
        }
 
    } else {
        [self hideHUD];
        [self SendTrendRequestWithContent:@"我今天发布的一条新的动态"];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _selectImageArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PostImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:postImageCellID forIndexPath:indexPath];
    cell.pictureImageView.image = _selectImageArray[indexPath.row];
    cell.deleteImageAction = ^(){
        [_selectImageArray removeObjectAtIndex:indexPath.row];
        [self.imageCollectionView reloadData];
    };
    if ([_selectImageArray[indexPath.row] isEqual:self.addImage]) {
        cell.deleteBtn.hidden = YES;
    }else{
        cell.deleteBtn.hidden = NO;
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self.descTextView resignFirstResponder];
    if (_selectImageArray.count - 1 == kMaxCount){
        [self showTitle:@"最多选9张图片，请重新选择"];
    } else if (_selectImageArray.count - 1 == indexPath.row  && [_selectImageArray containsObject:self.addImage]) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil
                                                                  preferredStyle:UIAlertControllerStyleActionSheet];
        __weak typeof(self) albumSelf = self;
        UIAlertAction *album = [UIAlertAction actionWithTitle:@"相册选取图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
            
            NSInteger count = 9 - _selectImageArray.count;
            if ([_selectImageArray containsObject:self.addImage]) {
                count += 1;
            }
            imagePickerVc.maxImagesCount = count;
            [self.imageCollectionView reloadData];
            
            [self presentViewController:imagePickerVc animated:YES completion:nil];
            
        }];
        //
        UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[GetPhoto sharedInstance] takePhotoWithController:self andIsCanEdit:NO];
            [[GetPhoto sharedInstance] setImage:^(UIImage *image) {
                
                [_selectImageArray addObject:image];
                NSInteger index = [_selectImageArray indexOfObject:_addImage];
                if (_selectImageArray.count > 1 && _selectImageArray.count <= kMaxCount) {
                    [_selectImageArray exchangeObjectAtIndex:index withObjectAtIndex:_selectImageArray.count - 1];
                    [albumSelf.imageCollectionView reloadData];
                }
                if (_selectImageArray.count == kMaxCount+1) {
                    [_selectImageArray removeObjectAtIndex:index];
                    [albumSelf.imageCollectionView reloadData];
                }
                
            }];
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alertVC addAction:album];
        [alertVC addAction:camera];
        [alertVC addAction:cancel];
        [self presentViewController:alertVC animated:YES completion:nil];
    }else if (indexPath.row < _selectImageArray.count && _selectImageArray.count > 0){
        NSMutableArray *photos = [[NSMutableArray alloc] init];
        
        MWPhoto *photo;
        BOOL displayActionButton = YES;
        BOOL displaySelectionButtons = NO;
        BOOL displayNavArrows = NO;
        BOOL enableGrid = YES;
        BOOL startOnGrid = NO;
        for (UIImage *img in _selectImageArray) {
            if (![img isEqual:self.addImage]) {
                photo = [MWPhoto photoWithImage:img];
                [photos addObject:photo];
            }
        }
        PIMWPhotoBrowserController *browser = [[PIMWPhotoBrowserController alloc] initWithPhotos:photos];
        [browser setSucceed:^(NSMutableArray *mutPhotos) {
            [_selectImageArray removeAllObjects];
            for (MWPhoto*img in mutPhotos) {
//                [_selectImageArray addObject:img.image];
            }
            [_selectImageArray addObject:self.addImage];
            [self.imageCollectionView reloadData];
        }];
        browser.displayActionButton = displayActionButton;
        browser.displayNavArrows = displayNavArrows;
        browser.displaySelectionButtons = displaySelectionButtons;
        browser.alwaysShowControls = displaySelectionButtons;
        browser.zoomPhotosToFill = YES;
        browser.enableGrid = enableGrid;
        browser.startOnGrid = startOnGrid;
        browser.enableSwipeToDismiss = NO;
        [browser setCurrentPhotoIndex:0];
        browser.photos = photos;
        
        [self.navigationController pushViewController:browser animated:YES];
    }

}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 15, 15);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat w = (kSCREEN_WIDTH - 60)/4;
    return CGSizeMake(w, w);
}

#pragma mark TZImagePickerControllerDelegate


// 用户选择好了图片，如果assets非空，则用户选择了原图。
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    if ([_selectImageArray containsObject:self.addImage]) {
        [_selectImageArray removeObject:self.addImage];
    }
    [_selectImageArray addObjectsFromArray:photos];
    
    if (_selectImageArray.count < 9) {
        if (_selectImageArray.count < 9) {
            [_selectImageArray addObject:self.addImage];
        }
        [self.imageCollectionView reloadData];
        
    }else if(_selectImageArray.count == 9){
        [self.imageCollectionView reloadData];
    }
}

#pragma mark -- UITextViewDelegate
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    self.placeHolder.hidden = YES;
    return YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.text.length == 0) {
        self.placeHolder.hidden = NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
